package com.drore.logapp.http.token;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.drore.app.LogRecordUtil;
import com.drore.app.utils.TimeLogUtils;
import com.drore.logapp.base.BaseApplication;
import com.drore.logapp.bean.BaseBean;
import com.drore.www.logbeansecret.bean.NetConnectBean;
import com.google.gson.Gson;

import java.net.SocketTimeoutException;

import rx.Subscriber;

/**
 * desc
 *
 * @author sixbing
 * @date 2018/12/12 9:58
 */

public abstract class MySubscriber<T> extends Subscriber<T> {
    private static String TAG = "MySubscriber";
    private Context mContext;

    public MySubscriber() {
        mContext = BaseApplication.getInstance();
    }

    abstract public void onSuccess(T data);

    abstract public void onFailed(String message);

    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        NetConnectBean netConnectBean = new NetConnectBean();
        netConnectBean.setRequestDetail(e.getMessage());
        netConnectBean.setRequestCode(404);
        netConnectBean.setRequestUrl(e.getMessage());
        netConnectBean.setSuccess(false);
        long time = TimeLogUtils.getCurrentTimeInLong();
        netConnectBean.setRequestStartTime(time);
        netConnectBean.setRequestEndTime(time);
        netConnectBean.setRequestDuration(0);
        LogRecordUtil.setNetDetail(netConnectBean, true);
        if (e instanceof SocketTimeoutException) {
//            StringBuilder stringBuffer = new StringBuilder("");
//            stringBuffer.append(e.getMessage()).append("\n");
//            StackTraceElement[] stackTraceElements = e.getStackTrace();
//            for (StackTraceElement stackTraceElement : stackTraceElements) {
//                stringBuffer.append("at " + stackTraceElement.getClassName()).append(stackTraceElement.getFileName())
//                        .append(stackTraceElement.getLineNumber()).append(stackTraceElement.getMethodName()).append("\n");
//            }
            Log.e(TAG, "连接超时:" + new Gson().toJson(netConnectBean) + "\n");
            onFailed("连接超时");
        } else {
            onFailed("请求或解析错误，请检查请求。" + e.getMessage());
        }
    }

    @Override
    public void onNext(T data) {
        if (data == null) {
            Toast.makeText(mContext, "数据获取失败！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (data instanceof BaseBean) {
            BaseBean baseBean = (BaseBean) data;
            if (baseBean.getStatus() == 200) {
                onSuccess(data);
            } else {
                onFailed("" + baseBean.getStatus());
            }
        } else {
            onSuccess(data);
        }
    }
}